//
//  AcanViewController.swift
//  01-HB二维码-基本结构搭建
//
//  Created by xmg on 16/5/21.
//  Copyright © 2016年 haibo. All rights reserved.
//

import UIKit
import CoreImage
class AcanViewController: UIViewController {
    @IBOutlet var QrCodeImage: UIImageView!
    @IBOutlet weak var inputText: UITextView!
    

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //实例化二维码滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        //恢复滤镜的默认属性
        filter?.setDefaults()
        //将传入的字符串转换成NSData
        let filterText = inputText.text
        let textData = filterText.dataUsingEncoding(NSUTF8StringEncoding)
        //通过KVC设置滤镜的inputMessage数据
        filter?.setValue(textData, forKey: "inputMessage")
        
        //设置二维码的纠错率
        filter?.setValue("H", forKey: "inputCorrectionLevel")
        //获取滤镜输出的图片
        guard var outPutImage = filter?.outputImage else {
            return
        }
        outPutImage = outPutImage.imageByApplyingTransform(CGAffineTransformMakeScale(10, 10))
        let outImage = UIImage(CIImage: outPutImage)
        //自定义二维码
        let image = UIImage(named: "465d0ed064a8393b644ec713963ab406")!
        let resultImage = createImage(outImage, centerImage: image)
        QrCodeImage.image = resultImage
        
    }
    func createImage(sourceImage: UIImage, centerImage: UIImage) -> UIImage {
        //开启图形上下文
        UIGraphicsBeginImageContext(sourceImage.size)
        sourceImage.drawInRect(CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height))
        //绘制中间的图标
        let W : CGFloat = 60
        let H : CGFloat = W
        let X : CGFloat = (sourceImage.size.width - W) * 0.5
        let Y : CGFloat = (sourceImage.size.height - H) * 0.5
        centerImage.drawInRect(CGRectMake(X, Y, W, H))
        //获取生成的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return image
        
    }
  }
